<template>
  <div class="scan-strategy">
    <ContentWrap>
      <el-form label-width="110px" ref="searchRef" :model="searchValue">
        <el-row>
          <el-col :span="6">
            <el-form-item label="模板名称" prop="templateName">
              <ns-input clearable placeholder="请输入模板名称" v-model="searchValue.templateName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="模板描述" prop="templateDesc">
              <ns-input clearable placeholder="请输入模板描述" v-model="searchValue.templateDesc" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="模板类型" prop="templateType">
              <el-select clearable placeholder="请输入模板类型" v-model="searchValue.templateType">
                <el-option label="数据库扫描" value="0" />
                <el-option label="文件服务器扫描" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select placeholder="请选择状态" clearable v-model="searchValue.status">
                <el-option label="开启" :value="1" />
                <el-option label="关闭" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="startTime">
              <el-date-picker
                v-model="searchValue.startTime"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button
              @click="search"
              type="primary"
              v-hasPermi="['asset:assetDiscovery:scanStrategy:search']"
              >搜索</el-button
            >
            <el-button @click="searchReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          @click="edit('create', {})"
          v-hasPermi="['asset:assetDiscovery:scanStrategy:create']"
          >新增</el-button
        >
        <el-button
          type="danger"
          @click="batchDelRow"
          plain
          :disabled="ids.length == 0"
          v-hasPermi="['asset:assetDiscovery:scanStrategy:batchDelete']"
          >删除</el-button
        >
      </el-form-item>
      <Dialog
        v-model="dialogVisible"
        :title="titleType == 'create' ? '添加模板' : '编辑模板'"
        width="30%"
        destroy-on-close
        close-on-click-modal
      >
        <el-form
          label-suffix="："
          label-width="100px"
          :rules="rules"
          :model="saveValue"
          ref="formRef"
        >
          <el-form-item label="模板名称" prop="templateName">
            <ns-input placeholder="请输入模板名称" v-model="saveValue.templateName" />
          </el-form-item>
          <el-form-item label="模板描述" prop="templateDesc">
            <ns-input
              placeholder="请输入模板描述"
              type="textarea"
              v-model="saveValue.templateDesc"
              :rows="3"
              :maxlength="500"
            />
          </el-form-item>
          <el-form-item label="模板类型" prop="templateType">
            <el-select
              placeholder="请选择模板类型"
              style="width: 100%"
              v-model="saveValue.templateType"
              :disabled="titleType != 'create'"
            >
              <el-option label="数据库扫描" value="0" />
              <el-option label="文件服务器扫描" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select placeholder="请选择状态" style="width: 100%" v-model="saveValue.status">
              <el-option label="开启" :value="1" />
              <el-option label="关闭" :value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save" :loading="loading">确定</el-button>
          </span>
        </template>
      </Dialog>
      <AsyncTable
        :fetchData="fetchData"
        v-bind="tableInfo"
        ref="tableRef"
        @selection-change="changeTable"
      />
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import * as scanStrategyApi from '@/api/asset/scanStrategy/index'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const dialogVisible = ref(false)
const formRef = ref()
const searchRef = ref()
const loading = ref(false)
const titleType = ref('')
const tableRef = ref()
const ids = ref<string[]>([])
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  templateName: '',
  templateDesc: '',
  templateType: '',
  status: '',
  startTime: []
})
const saveValue = ref({
  markedTemplateId: '',
  scanCycle: 'month',
  templateName: '',
  scanCycleMethod: 1,
  templateDesc: '',
  templateType: '0',
  status: 1,
  marked: '1',
  scanCycleType: 1,
  dbScanType: 0,
  scanSamples: 0,
  scanSamplesLine: 10,
  scanSamplesType: 0,
  fileScanType: 0,
  fileSize: 0,
  fileType: '1',
  likeThreshold: 0,
  likeSignAlgo: [],
  priority: '',
  moduleId: '',
  filePriority: '',
  modulePriority: '',
  rulePriority: '',
  dataMarkType: [],
  isSaveResult: 1,
  fileScanClass: [],
  field15: '0',
  field14: 23,
  field11: 6,
  field10: 5,
  field12: 20,
  field13: '0'
})

/**
 * @description: 重置dialog弹窗表单
 */
const resetForm = () => {
  saveValue.value = {
    markedTemplateId: '',
    scanCycle: 'month',
    templateName: '',
    scanCycleMethod: 1,
    templateDesc: '',
    templateType: '0',
    status: 1,
    marked: '1',
    scanCycleType: 1,
    dbScanType: 0,
    scanSamples: 0,
    scanSamplesLine: 10,
    scanSamplesType: 0,
    fileScanType: 0,
    fileSize: 0,
    likeThreshold: 0,
    likeSignAlgo: [],
    priority: '',
    moduleId: '',
    filePriority: '',
    modulePriority: '',
    rulePriority: '',
    dataMarkType: [],
    fileScanClass: [],
    isSaveResult: 1,
    fileType: '1',
    field15: '0',
    field14: 23,
    field11: 6,
    field10: 5,
    field12: 20,
    field13: '0'
  }
}

/**
 * @description:重置搜索表单
 */
const searchReset = () => {
  searchRef.value.resetFields()
  search()
}

/**
 * @description: 选取表格行时获取id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const rules = reactive({
  templateName: [
    {
      required: true,
      message: '模板名称不能为空',
      trigger: 'blur'
    }
  ],
  templateType: [
    {
      required: true,
      trigger: 'change',
      message: '模板类型不能为空'
    }
  ],
  status: [
    {
      required: true,
      trigger: 'change',
      message: '状态不能为空'
    }
  ]
})
const tableInfo = reactive({
  columns: [
    {
      type: 'selection'
    },
    {
      prop: 'templateName',
      label: '模板名称'
    },
    {
      prop: 'templateDesc',
      label: '模板描述'
    },
    {
      label: '模板类型',
      render: ({ row }) => {
        return <span>{row.templateType == '0' ? '数据库扫描' : '文件服务器扫描'}</span>
      }
    },
    {
      label: '状态',
      render: ({ row }) => {
        return <span>{row.status == 1 ? '开启' : '关闭'}</span>
      }
    },
    {
      label: '创建时间',
      render: ({ row }) => {
        return <span>{dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      label: '操作',
      type: 'operation',
      render: ({ row }) => {
        return (
          <>
            <el-button
              link
              type="primary"
              onClick={() => detail(row)}
              v-hasPermi={[['asset:assetDiscovery:scanStrategy:detail']]}
            >
              策略设计
            </el-button>
            <el-button
              link
              type="primary"
              onClick={() => edit('edit', row)}
              v-hasPermi={[['asset:assetDiscovery:scanStrategy:edit']]}
            >
              编辑
            </el-button>
            <ns-button
              link
              confirm
              type="danger"
              style="margin-left:6px"
              onClick={() => del(row)}
              v-hasPermi={[['asset:assetDiscovery:scanStrategy:singleDelete']]}
            >
              删除
            </ns-button>
          </>
        )
      }
    }
  ],
  data: []
})
const fetchData = async ({ page, pageSize }) => {
  const { data, count } = await scanStrategyApi.getScanPolicyTemplatePage({
    page: page,
    pageSize,
    ...searchValue.value
  })
  return { data, count }
}

function batchDelRow() {
  proxy.$modal
    .confirm(`确定要删除选择的策略吗？`)
    .then(() => {
      scanStrategyApi.deleteScanPolicyTemplate(ids.value).then(({ code }) => {
        code === 200 && ElMessage.success('删除成功')
        code === 200 && search()
        if (code === 200) ids.value = []
      })
    })
    .catch(() => {})
}
const del = (row) => {
  scanStrategyApi.deleteScanPolicyTemplate([row.id]).then(({ code }) => {
    code === 200 && ElMessage.success('删除成功')
    code === 200 && search()
  })
}

const detail = (row) => {
  proxy?.$Drawer({
    params: {
      id: row.id,
      type: row.templateType,
      callBack: search
    },
    title: `策略设计`,
    size: '70%',
    component: import('./detail.vue')
  })
}

const edit = (type, row) => {
  titleType.value = type
  dialogVisible.value = true
  if (type == 'edit') {
    scanStrategyApi.getScanPolicyTemplate(row.id).then((res) => {
      saveValue.value = res
    })
  } else {
    resetForm()
  }
}
const save = async () => {
  const v = await formRef.value.validate()
  if (v) {
    loading.value = true
    titleType.value == 'create'
      ? scanStrategyApi
          .createScanPolicyTemplate(saveValue.value)
          .then(({ code }) => {
            code === 200 && ElMessage.success('添加成功')
            code === 200 && search()
            dialogVisible.value = false
            loading.value = false
          })
          .catch(() => {
            loading.value = false
          })
      : scanStrategyApi
          .updateScanPolicyTemplate({ ...saveValue.value, likeSignAlgo: [] })
          .then(({ code }) => {
            code === 200 && ElMessage.success('编辑成功')
            code === 200 && search()
            dialogVisible.value = false
            loading.value = false
          })
          .catch(() => {
            loading.value = false
          })
  }
}
</script>

<style lang="scss">
.scan-strategy {
  .el-form .el-select {
    width: 100%;
  }
  .ns-input {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
}
</style>
